import axios from 'axios';

initPdf();

let pdf, preview, previreContext, previewWidth = 0, previewHeight = 0;
let canvasArray = [];
let onImage = function(){};
let pdfJsLoaded=false;
let origin = '';
let onPdfLoaded = function(){};
function initPdf(){
    origin = window.location.origin;
    importPdfJs((pdfjsLib)=>{
        preview = document.createElement('canvas');
        preview.setAttribute('style','position:fixed;top:0;left:0;z-index:1000')
        document.body.append(preview);
        previreContext = preview.getContext('2d');
        pdfjsLib.GlobalWorkerOptions.workerSrc = origin+'/static/pdf.worker.min.js';
        onPdfLoaded();
    })
}

function importPdfJs(cb){
    if(pdfJsLoaded){cb(pdfjsLib);return;}
    let script = document.createElement('script');
    script.onload = function(){
        cb(pdfjsLib);
        pdfJsLoaded = true;
    }
    script.src = origin+'/static/pdf.min.js';
    document.body.appendChild(script);
}

export function convertPdfToImgUrl(pdfUrl, cb){
    debugger
    if(typeof cb === 'function') {onImage=cb};
    axios({
        url: pdfUrl,
        method: 'get',
        responseType: 'blob', // 必须要填写
        headers:{
            'Content-Type':'application/x-www-form-urlencoded', 
            'x-locale':'zh-CN'
        }
    }).then(function (res) {
        debugger
        let blob = new Blob([res.data], {type: 'application/pdf'});
        let file = new File([blob], 'pdf.pdf', {type: 'application/pdf', lastModified: Date.now()});
        if(pdfJsLoaded){
            loadPDFToImgUrl(file)
        }else{
            onPdfLoaded = ()=>{
                loadPDFToImgUrl(file)
            }
        }
    }).catch(function (err) {
        console.log(err)
    })
}

function loadPdf(pdfUrl){
}

function loadPDFToImgUrl(file) {
    let reader = new FileReader();
    reader.onload = (e)=>{
        showPDF(e.target.result)
    };
    reader.readAsDataURL(file);
}
function showPDF(url) {
    let loadingTask = pdfjsLib.getDocument(url);
    loadingTask.promise.then(function(doc) {
        pdf = doc;
        // pageNum = 1;
        // preview.hidden = false;
        readerAllPage()
    }, function(reason) {
        alert(reason)
    });
}
function readerAllPage(){
    renderSinglePage(1);
}

function renderSinglePage(pageNum){
    let canvas = document.createElement('canvas');
    // document.body.append(canvas);
    // canvas.setAttribute('style','position:fixed;top:0;left:0;z-index:1000')
    let context = canvas.getContext('2d');
    pdf.getPage(pageNum).then(function(page) {
        let scale = 1;
        let viewport = page.getViewport({
            scale: scale
        });
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        previewWidth = viewport.width;
        previewHeight += viewport.height;
        let renderContext = {
            canvasContext: context,
            viewport: viewport
        };
        page.render(renderContext).promise.then(()=>{
            canvasArray.push(canvas);
            if(pageNum<pdf.numPages){
                renderSinglePage(pageNum+1);
            }else{
                renderAllCanvas();
            }
        });
    });
}
function renderAllCanvas(){
    preview.width = previewWidth;
    preview.height = previewHeight;
    canvasArray.forEach((canvas,index)=>{
        previreContext.drawImage(canvas, 0 , ((index === 0)?0:canvasArray[index-1].height));
    });
    onImage(preview.toDataURL("image/png"));
    document.body.removeChild(preview)
}
